// Copyright 2010 The Go Example Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.


package main

import (
	"fmt"
	"json"
	"os"
)

//define a person info type
type person struct {
	name string
	age  int
	sex  string
}

func (p *person) String() string {
	var content string
	content = "Name:\t" + p.name
	content += "\nAge: \t" + fmt.Sprint(p.age)
	content += "\nSex:\t" + p.sex
	return content
}

func main() {
	//define filename
	var fileName string = "data/person.json"
	//Create File 
	//创建文件
	fn, err := os.Open(fileName, os.O_CREATE, 0444)

	if err != nil {
		// when can't create file ,the program exit
		//创建文件失败时退出
		fmt.Print("can't create file")
		os.Exit(1)
	}

	//Close File 
	//关闭文件
	defer fn.Close()

	p1 := &person{"Jack", 22, "man"}

	fmt.Print("Person 1 :\n")
	fmt.Println(p1)

	var p2 *person = new(person)

	p2.name = "魏仁言"
	p2.age = 24
	p2.sex = "男"

	fmt.Print("Person 2 :\n")
	fmt.Println(p2)

	var p3 *person = &person{"Bill", 25, "man"}

	fmt.Print("Person 3 :\n")
	fmt.Println(p3)

	//Create Json Encoder
	//创建Json 编码器
	ml := json.NewEncoder(fn)

	//Encode var p1
	//将变量p1进行Json编码输出
	ml.Encode(p1)

	//Encode var p2
	//将变量p2进行Json编码输出
	ml.Encode(p2)

	//Encode var p3
	//将变量p3进行Json编码输出
	ml.Encode(p3)
}
